package com.simdo.g768.Fragment;

import static com.simdo.g768.MainActivity.device;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

import com.g768.MessageControl.MessageController;
import com.github.mikephil.charting.charts.BarChart;
import com.simdo.g768.Bean.IMSIState;
import com.simdo.g768.Bean.ImsiBean;
import com.simdo.g768.MainActivity;
import com.simdo.g768.R;
import com.simdo.g768.Util.AppLog;
import com.simdo.g768.Util.BarChartUtil;
import com.simdo.g768.Util.DateUtil;
import com.simdo.g768.Util.ParseDataUtil;
import com.simdo.g768.Util.TextTTS;
import com.simdo.g768.ZApplication;

import java.text.MessageFormat;

public class TraceChildFragment extends Fragment {

    Context mContext;

    public TraceChildFragment(Context context) {
        this.mContext = context;
    }
    public TraceChildFragment() {
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppLog.I("TraceChildFragment onCreate");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        AppLog.I("TraceChildFragment onCreateView");

        View root = inflater.inflate(R.layout.child_pager_trace, container, false);

        initView(root);

        initObject();
        return root;
    }

    TextView tv_up_imsi;
    TextView tv_arfcn_pci;
    TextView tv_rsrp_value, tv_up_num, tv_up_time;
    private BarChartUtil barChartUtil;

    private boolean isSay = true;
    private int count = 0;
    private String type = "";
    private String imsi = "";
    private String plmnType = "";
    private String arfcnPci = "";

    private void initView(View root) {
        // TTS语音播报图标
        ImageView iv_tts = root.findViewById(R.id.iv_tts);
        iv_tts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isSay = !isSay;
                iv_tts.setImageResource(isSay ? R.mipmap.sound_select_icon : R.mipmap.sound_no_select_icon);
            }
        });

        tv_up_imsi = root.findViewById(R.id.tv_up_imsi);
        tv_up_imsi.setTag("");
        tv_up_imsi.setCompoundDrawablePadding(10);
        tv_arfcn_pci = root.findViewById(R.id.tv_arfcn_pci);
        tv_rsrp_value = root.findViewById(R.id.tv_rsrp_value);
        tv_up_num = root.findViewById(R.id.tv_up_num);
        tv_up_time = root.findViewById(R.id.tv_up_time);

        //柱状图
        BarChart char_bar = root.findViewById(R.id.char_bar);
        barChartUtil = new BarChartUtil(char_bar);
        barChartUtil.setXYAxis(110, 0, 5);
        barChartUtil.addBarDataSet(mContext.getString(R.string.bar_view), getResources().getColor(R.color.main_color));

        initText();
        updateConfigUi();
    }

    private void initObject() {
        TextTTS.build().initTTS();
    }

    private void initText() {
        if (tv_up_num == null) return;
        tv_up_num.setText(MessageFormat.format(mContext.getString(R.string.up_count), count));
        tv_up_time.setText(MessageFormat.format(mContext.getString(R.string.update_time), DateUtil.formateTimeHMS(System.currentTimeMillis())));
        if (imsi.isEmpty()) tv_up_imsi.setText("");
        else tv_up_imsi.setText(MessageFormat.format("{0} {1} {2}", plmnType, type, imsi));
        tv_rsrp_value.setText("00");
        tv_arfcn_pci.setText("");
    }

    public void setConfigInfo(int cell_id, String arfcn, String pci) {
        String info = arfcn + "/" + pci;
        if (arfcnPci.equals(info)) return;
        AppLog.I("TraceChildFragment setConfigInfo cell_id = " + cell_id + ", arfcn = " + arfcn + ", pci = " + pci);
        arfcnPci = info;
        if (arfcnPci.length() == 1) arfcnPci = "";
        type = arfcn.length() < 6 ? "4G" : "5G";
        updateConfigUi();
    }

    private boolean isSayLost = false;
    private final boolean[] cellUp = {false, false, false, false, false, false};
    private final boolean[] cellEnable = {false, false, false, false, false, false};

    public void resetRsrp(ImsiBean bean) {
        isSayLost = false;
        for (int i = 0; i < 6; i++){
            cellUp[i] = false;
            cellEnable[i] = false;
        }
        if (bean == null) imsi = ZApplication.getInstance().isTrace ? "" : mContext.getString(R.string.please_select_in_list);
        arfcnPci = "";
        type = "";
        plmnType = "";
        count = 0;
        if (barChartUtil != null) {
            for (int i = 0; i < 15; i++) {
                barChartUtil.addEntry(0, -999);
            }
        }
        initText();
    }

    private void say(String sayInfo, boolean b) {
        if (isSay) TextTTS.build().play(sayInfo, b);
    }

    int cell_id = 0;
    public boolean setRsrpValue(){
        boolean isTrue = false;
        int rsrp = -1;
        for (int i = 0; i < 6; i++){
            int cellRsrp = ParseDataUtil.build().getRxByMode(2, i);
            if (cellRsrp > 5) {
                rsrp = cellRsrp;
                cell_id = i;
                break;
            }
        }
        if (rsrp > 5) isTrue = true;
        setRsrpValue(cell_id, rsrp);
        return isTrue;
    }

    public void setRsrpValue(int cell_id, int rsrp) {
        if (tv_rsrp_value == null) return;

        if (rsrp < 5) rsrp = -1;

        if (rsrp == -1 && tv_rsrp_value.getText().toString().equals("00")) return;

        if (rsrp == -1) {
            if (isSayLost) return;
            cellUp[cell_id] = false;
            cellEnable[cell_id] = false;
            if (ZApplication.getInstance().isTrace) MessageController.build().setSpecialMode(device.getId(), cell_id, false);
            say(mContext.getString(R.string.trace_lose), true);
            isSayLost = true;
        } else {
            isSayLost = false;
            if (!cellUp[cell_id]){
                cellUp[cell_id] = true;
                Vibrator vib = (Vibrator) mContext.getSystemService(Service.VIBRATOR_SERVICE);
                vib.vibrate(1000);
            }
            if (!cellEnable[cell_id] && MainActivity.getInstance().enableSpecial){
                cellEnable[cell_id] = true;
                if (ZApplication.getInstance().isTrace) MessageController.build().setSpecialMode(device.getId(), cell_id, MainActivity.getInstance().enableSpecial);
            }

            say(String.valueOf(rsrp), false);
        }

        tv_rsrp_value.setText(String.valueOf(rsrp));
        tv_arfcn_pci.setText(arfcnPci);
        barChartUtil.addEntry(0,rsrp);
        tv_up_time.setText(MessageFormat.format(mContext.getString(R.string.update_time), DateUtil.formateTimeHMS(System.currentTimeMillis())));
    }

    public void updateCount(){
        count++;
        if (tv_up_num != null) tv_up_num.setText(MessageFormat.format(mContext.getString(R.string.up_count), count));
    }

    public boolean[] getCellUp(){
        return cellUp;
    }

    private void updateConfigUi() {
        if (tv_up_imsi == null) return;
        AppLog.I("TraceChildFragment updateConfigUi imsi = " + imsi + ", arfcnPci = " + arfcnPci);
        tv_up_imsi.setText(MessageFormat.format("{0} {1} {2}", plmnType, type, imsi));
        tv_arfcn_pci.setText(arfcnPci);
    }

    public void setConfigInfo(String imsi, int arfcn){
        if (this.imsi.equals(imsi)) return;
        ImsiBean imsiBean = new ImsiBean(IMSIState.IMSI_NOW, imsi, String.valueOf(arfcn), "", 0, System.currentTimeMillis(), 0, 0, "");
        imsiBean.setUpCount(0);
        setConfigInfo(imsiBean);
    }

    public void setConfigInfo(ImsiBean bean) {
        count = bean.getUpCount();
        if (Integer.parseInt(bean.getArfcn()) > 100000) type = "5G";
        else type = "4G";
        imsi = bean.getImsi();
        if (!ZApplication.getInstance().isShowAllImsi) imsi = imsi.substring(0,5) + "****" + imsi.substring(11);

        String tracePlmn = imsi.substring(0, 5);
        if (barChartUtil != null) {
            for (int i = 0; i < 15; i++) {
                barChartUtil.addEntry(0, -999);
            }
            tv_up_imsi.setTag("");
            tv_up_imsi.setCompoundDrawables(null, null, null, null);
        }
        switch (tracePlmn) {
            case "46003":
            case "46005":
            case "46011":
            case "46012":
                plmnType = "电信";
                break;
            case "46000":
            case "46002":
            case "46004":
            case "46007":
            case "46008":
            case "46013":
                plmnType = "移动";
                break;
            case "46001":
            case "46006":
            case "46009":
            case "46010":
                plmnType = "联通";
                break;
            case "46015":
                plmnType = "广电";
                break;
        }
        initText();
        updateConfigUi();
    }

    public void setIphoneIcon(int phoneType, int rsrp) {
        if (tv_up_imsi == null) return;
        if (phoneType > 1 && rsrp > MainActivity.getInstance().showMinRsrp){
            if (tv_up_imsi.getTag().toString().equals("show")) return;
            Drawable iphone = null;
            switch (phoneType){
                case 2:
                case 3:
                case 4:
                    iphone = mContext.getResources().getDrawable(R.mipmap.iphone);
                    break;
                case 5:
                case 12:
                    iphone = mContext.getResources().getDrawable(R.mipmap.sansung);
                    break;
            }
            // 这一步必须要做,否则不会显示.
            iphone.setBounds(0, 0, iphone.getMinimumWidth() / 3, iphone.getMinimumHeight() / 3);
            tv_up_imsi.setTag("show");
            tv_up_imsi.setCompoundDrawables(null, null, iphone, null);
            return;
        }
        if (tv_up_imsi.getTag().toString().isEmpty()) return;
        tv_up_imsi.setTag("");
        tv_up_imsi.setCompoundDrawables(null, null, null, null);
    }
}